//
//  WKBPayChooseMessageView.m
//  WKCarInsurance
//
//  Created by sunyang on 17/8/16.
//  Copyright © 2017年 wkbins. All rights reserved.
//

#import "SLCodeInputView.h"
#import "UIButton+IANActivityView.h"
#import "NSString+JXCommon.h"

@interface SLCodeInputView ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UILabel *titleLb;
@property (weak, nonatomic) IBOutlet UITextField *codeField;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UIButton *firstBtn;
@property (weak, nonatomic) IBOutlet UIButton *secondBtn;
@property (strong, nonatomic) UIControl *controlForDismiss;
@property (strong, nonatomic) NSTimer *timer;
@property (assign, nonatomic) NSInteger intervalTime;
@property (nonatomic, assign) CGFloat lastSendcodeTime;

@end

@implementation SLCodeInputView

- (void)awakeFromNib {
    [super awakeFromNib];
    self.codeField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    self.codeField.returnKeyType = UIReturnKeyDone;
    self.codeField.delegate = self;
    UIView *blankView = [[UIView alloc] initWithFrame:CGRectMake(self.codeField.frame.origin.x,self.codeField.frame.origin.y,12.0, self.codeField.frame.size.height)];
    self.codeField.leftView = blankView;
    self.codeField.leftViewMode =UITextFieldViewModeAlways;  // 这里是用来设置leftView的实现时机的
}

- (void)waitNextSend{
    self.lastSendcodeTime = [[NSDate date] timeIntervalSince1970];
    self.codeBtn.enabled = NO;
    JLAsyncRun(^{
        while (YES) {
            CGFloat time = [[NSDate date] timeIntervalSince1970];
            if (time - self.lastSendcodeTime < 120) {
                JLAsyncRunInMain(^{
                    self.codeBtn.fsFontSize(15).fsText([NSString stringWithFormat:@"%@s",@((NSInteger)(120+self.lastSendcodeTime - time))]);
                });
            } else {
                JLAsyncRunInMain(^{
                    self.codeBtn.enabled = YES;
                    self.codeBtn.fsText(@"发送验证码");
                });
                break;
            }
            [NSThread sleepForTimeInterval:1];
        }
    });
}
- (IBAction)codeBtnAction:(UIButton *)sender {
    __weak typeof(self) weakSelf = self;
    sender.enabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        sender.enabled = YES;
    });
    if (self.delegate && [self.delegate respondsToSelector:@selector(codeButtonClick:completion:)]) {
        __strong typeof(self) strongSelf = weakSelf;
        [self.delegate codeButtonClick:self.codeField.text completion:^{
            [strongSelf waitNextSend];
        }];
    }

}
- (IBAction)firstBtnAction:(UIButton *)sender {
//    [self dismiss];
    if (self.delegate && [self.delegate respondsToSelector:@selector(codeAlertFirstBtnClick:)]) {
        [self.delegate codeAlertFirstBtnClick:self.codeField.text];
    }

}

- (IBAction)secondBtnAction:(UIButton *)sender {
    if ([NSString isEmptyWithString:_codeField.text]) {
        WKBToastInfoInView(@"请输入验证码", self);
        return;
    }
    [self.codeField resignFirstResponder];
    sender.enabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        sender.enabled = YES;
    });
    if (self.delegate && [self.delegate respondsToSelector:@selector(codeAlertSecondBtnClick:view:completion:)]) {
        [self.delegate codeAlertSecondBtnClick:self.codeField.text view:self completion:^(NSString *message) {
//            hud.label.text = message;
        }];
    }
}

- (void)updateCodeAlertViewWithTitle:(NSString *)title{
    self.titleLb.text = [NSString stringWithFormat:@"请输入手机%@收到的短信验证码", title];
    [self show];
}

- (void)calculateRemainTime {
    //如果当前时间已经超过 核保时间 则更新为失效，否则显示倒计时
    if (_timer == nil) {
        _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
        _intervalTime = 60;
        self.codeBtn.enabled = NO;
        [_timer fire];
    }
}
- (void)timerAction {
    _intervalTime--;
    if (_intervalTime > 0) {
        [self.codeBtn setTitle:[NSString stringWithFormat:@"%ld秒", _intervalTime] forState:UIControlStateNormal];
    }else{
        [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_timer invalidate];
        _timer = nil;
        self.codeBtn.enabled = YES;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.codeField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [self animateTextField:textField up:NO];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [self animateTextField:textField up:YES];
}

- (void)animateTextField:(UITextField *)textField up: (BOOL) up
{
    const int movementDistance = 97; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed
    int movement = (up ? -movementDistance : movementDistance);
    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.frame = CGRectOffset(self.frame, 0, movement);
    [UIView commitAnimations];
}


#pragma mark - show or hide self
- (void)show
{
    [self refreshTheUserInterface];
    UIWindow *keywindow = [[UIApplication sharedApplication] keyWindow];
    if (self.controlForDismiss){
        [keywindow addSubview:self.controlForDismiss];
    }
    [keywindow addSubview:self];
    self.center = CGPointMake(keywindow.bounds.size.width/2.0f,
                              keywindow.bounds.size.height/2.0f);
}

- (void)dismiss
{
    [self animatedOut];
}

- (void)refreshTheUserInterface
{
    if (nil == _controlForDismiss)
    {
        _controlForDismiss = [[UIControl alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _controlForDismiss.backgroundColor = [UIColor colorWithRed:.16 green:.17 blue:.21 alpha:.5];
    }
}

#pragma mark - Animated Mthod
- (void)animatedOut
{
    [_timer invalidate];
    _timer = nil;
    if (self.controlForDismiss){
        [self.controlForDismiss removeFromSuperview];
    }
    [self removeFromSuperview];
}

- (void)showShadowView:(BOOL)willShow{
    if (willShow) {
        UIWindow *keywindow = [[UIApplication sharedApplication] keyWindow];
        if (self.controlForDismiss){
            [keywindow addSubview:self.controlForDismiss];
        }
        [keywindow bringSubviewToFront:self];
    }else{
        if (self.controlForDismiss){
            [self.controlForDismiss removeFromSuperview];
        }
    }
}




@end
